
import Router from 'koa-router';
import { User, Counter, Role, Menu } from '../../models/models.js';
import util from '../../utils/util.js';
import jwt from 'jsonwebtoken';
import md5 from 'md5';

const router = new Router();
router.prefix('/users')
// 获取自增ID的函数
async function getNextSequenceValue(sequenceName) {
  const sequenceDocument = await Counter.findByIdAndUpdate(
    sequenceName,
    { $inc: { sequence_value: 1 } },
    { new: true, upsert: true }
  );
  return sequenceDocument.sequence_value;
}

// 用户登录
router.post('/login', async (ctx) => {
  try {
    const { userName, userPwd } = ctx.request.body;
    /**
     * 返回数据库指定字段，有三种方式
     * 1. 'userId userName userEmail state role deptId roleList'
     * 2. {userId:1,_id:0}
     * 3. select('userId')
     */
    const res = await User.findOne({
      userName,
      userPwd: md5(userPwd)
    }, 'userId userName userEmail state role deptId roleList')

    if (res) {
      const data = res._doc;
      const token = jwt.sign({
        data
      }, 'imooc', { expiresIn: '1h' })
      data.token = token;
      ctx.body = util.success(data)
    } else {
      ctx.body = util.fail("账号或密码不正确")
    }
  } catch (error) {
    ctx.body = util.error(error.msg)
  }
})

router.post('/add', async (ctx) => {
  try {
    const userData = ctx.request.body;
    const user = await User.create(userData);
    // 返回用户信息，不包含密码
    const userResponse = user;
    ctx.status = 201;
    ctx.body = {
      success: true,
      data: userResponse
    };
  } catch (error) {
    ctx.body = util.fail(error.msg)
  }
})

// 用户列表
router.get('/list', async (ctx) => {
  const { userId, userName, state } = ctx.request.query;
  const { page, skipIndex } = util.pager(ctx.request.query)
  let params = {}
  if (userId) params.userId = userId;
  if (userName) params.userName = userName;
  if (state && state != '0') params.state = state;
  try {
    // 根据条件查询所有用户列表
    // _id: 0, 
    const query = User.find(params, { userPwd: 0 })
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await User.countDocuments(params);
    ctx.body = util.success({
      page: {
        ...page,
        total
      },
      list
    })
  } catch (error) {
    ctx.body = util.fail(`查询异常:${error.stack}`)
  }
})

// 获取全量用户列表
router.get('/all/list', async (ctx) => {
  try {
    // const list = await User.find({}, "userId userName userEmail")
    const list = await User.find().select('-userPwd');
    ctx.body = util.success(list)
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

// 用户删除/批量删除
router.post('/delete', async (ctx) => {
  // 待删除的用户Id数组
  const { _ids } = ctx.request.body
  const res = await User.deleteMany({ _id: { $in: _ids } });
  if (res.deletedCount) {
    ctx.body = util.success(res, `共删除成功${res.deletedCount}条`)
    return;
  }
  ctx.body = util.fail('删除失败');
})


// 用户新增/编辑
router.post('/operate', async (ctx) => {
  const { _id, userId, userName, userEmail, mobile, job, state, roleList, deptId, action, nickName } = ctx.request.body;
  console.log(111)
  if (action == 'add') {
    if (!userName || !userEmail || !deptId) {
      ctx.body = util.fail('参数错误', util.CODE.PARAM_ERROR)
      return;
    }
    const res = await User.findOne({ $or: [{ userName }, { userEmail }] }, '_id userName userEmail')
    if (res) {
      ctx.body = util.fail(`系统监测到有重复的用户，信息如下：${res.userName} - ${res.userEmail}`)
    } else {
      const userIds = await getNextSequenceValue('userId');
      console.log(userIds)
      debugger
      try {
        const user = await User.create({
          nickName: nickName,
          userId: userIds,
          userName,
          userEmail,
          mobile,
          job,
          state,
          roleList,
          deptId,
          userPwd: md5('123456'),
          role: 1, //默认普通用户s
        });
        ctx.body = util.success(user, '用户创建成功');
      } catch (err) {
        ctx.body = util.fail(err.message);
      }
    }
  } else {
    if (!deptId) {
      ctx.body = util.fail('部门不能为空', util.CODE.PARAM_ERROR)
      return;
    }
    try {
      const res = await User.findByIdAndUpdate({ _id }, {
        nickName,
        userName,
        userEmail,
        mobile,
        job,
        state,
        roleList,
        deptId,
        userPwd: md5('123456'),
        role: 1, //默认普通用户s
      })
      ctx.body = util.success({}, '更新成功')
    } catch (error) {
      ctx.body = util.fail(error.stack, '更新失败')
    }
  }
})
// 获取用户对应的权限菜单
router.get("/getPermissionList", async (ctx) => {

  let authorization = ctx.request.headers.authorization
  let { data } = util.decoded(authorization)//解析token token 加密时候保存了用户信息
  console.log('411', data)
  let menuList = await getMenuList(data.role, data.roleList);
  let actionList = getAction(JSON.parse(JSON.stringify(menuList)))
  ctx.body = util.success({ menuList, actionList });
})

async function getMenuList(userRole, roleKeys) {
  let rootList = []
  if (userRole == 0) {
    rootList = await Menu.find({}) || []
  } else {
    // 根据用户拥有的角色，获取权限列表
    // 现查找用户对应的角色有哪些
    let roleList = await Role.find({ _id: { $in: roleKeys } })
    let permissionList = []
    roleList.map(role => {
      let { checkedKeys, halfCheckedKeys } = role.permissionList;
      permissionList = permissionList.concat([...checkedKeys, ...halfCheckedKeys])
    })

    permissionList = [...new Set(permissionList)]
    rootList = await Menu.find({ _id: { $in: permissionList } })
  }
  return util.getTreeMenu(rootList, null, [])
}

function getAction(list) {
  let actionList = []
  const deep = (arr) => {
    while (arr.length) {
      let item = arr.pop();
      if (item.action) {
        item.action.map(action => {
          actionList.push(action.menuCode)
        })
      }
      if (item.children && !item.action) {
        deep(item.children)
      }
    }
  }
  deep(list)
  return actionList;
}
// module.exports = router
export default router;
